$(function () {
    //加载商品
    getShopData(false,true);

    $("body").on('click','#updateAddressBtn',function (event) {//修改收货地址
        var parent = $(this).parents('div.blank-item');
        var addressId = $(parent).data('id');
        event.stopPropagation();
        if(addressId == null || addressId == 'undefined'){
            addressId = 0;
        }
        initSaveAddress(addressId ,saveAddressCallback);
    }).on('click','#addAddRessBtn',function () {//添加收获地址
        var id = $(this).parents('div.blank-item').data('id');
        if(id == null || id == 'undefined'){
            id = 0;
        }
        initSaveAddress(id ,saveAddressCallback);
    }).on('click','.delete-shop-box',function () {//删除购物车
        var _this = $(this);
        var parentEM =  _this.parent('div').parent("aside").parent('section');
        //购物车ID
        var shopCartId = $(parentEM).find('input[name="shopCartId"]').val();

        icModale(2,'提示','确认要删除该商品？','确认',null,function (index, ele) {
            //删除购物车
            deleteShopCart(shopCartId,function () {
                layer.close(index);
                //重新加载商品
                getShopData(false,true);
            });
        });

    }).on("click", ".minus-btn", function () {//减购买量
        var _this = $(this);
        updateBuyNum(_this, 1);
    }).on('click', ".add-btn", function () {//加购买量
        var _this = $(this);
        updateBuyNum(_this, 2);
    }).on('change', ".buy-num-in", function () {//改变购买量
        var _this = $(this);
        updateBuyNum(_this, 3);
    }).on('click','#user-address-list .user-address-list-box',function () {//选择地址
        $(this).addClass("active");
        $(this).parent().siblings().find(".user-address-list-box").removeClass('active');
    }).on('click','.pay-type-sel-box',function () {//选择支付方式
        $(".pay-type-sel-box").removeClass("active");
        $(this).addClass('active');
    }).on('change','#activity-sel-box',function () {//选择活动
        getShopData(true,false);
    }).on('change','#coupon-code-sel-box',function () {//选择优惠券
        var couponCode = $(this).val();
        if(couponCode==null || $.trim(couponCode)==''){
            $("#coupon-code").val('');
        }else{
            $("#coupon-code").val(couponCode);
        }
        $("#coupon-code").removeAttr("readonly");
        $("#but-sub-box").show();
        $("#but-cancel-box").hide();
        getShopData(true,false);
    }).on('click','#but-sub-box',function () {//确认使用优惠券
        var couponCode = $("#coupon-code").val();
        if(couponCode ==null || $.trim(couponCode)==''){
            icModale(0,'','请选择或输入优惠券编码');
            return;
        }
        $(this).hide();
        $("#but-cancel-box").show();
        $("#coupon-code").attr('readonly','readonly');
        getShopData(true,false);
    }).on('click','#but-cancel-box',function () {//取消优惠券的使用
        $("#coupon-code").removeAttr('readonly');
        $("#coupon-code-sel-box").val('');
        $("#but-sub-box").show();
        $("#but-cancel-box").hide();
        $("#coupon-code").val('');
        getShopData(true,false);
    }).on('click','#create-order-but',function () {//创建订单号
        var payType = getPayType();
        var activityId = $("#activity-sel-box").val();
        var couponCode = getCouponCode();
        var addressId  = 0;
        var address = '';
        var obj = getAddressData();
        if(obj!=null){
            addressId = obj.addressId;
            address = obj.address;
        }
        var shareKey = $("#shareKey").val();
        $.ajax({
            url:baseloaction +'/web/uc/order/createWebOrder',
            type:'post',
            dataType:'json',
            async:false,
            data:{
                'payType':payType,
                'orderType': orderType,
                'shopData': shopData,
                'addressId': addressId,
                'address': address,
                'activityId':activityId,
                'couponCode':couponCode
            },
            success:function (result) {
                if(result.success==true){
                    layer.open({
                        type: 1,
                        title: '提示',
                        content: '支付结果是完成或遇到问题？',
                        btn: [' 完成支付', '遇到问题'],
                        area: 'auto',
                        btnAlign: 'c',
                        shade: [0.3, '#000000'],
                        skin: 'lay_ppComment__wrap',
                        yes: function(index, ele){
                           window.location.href = baseloaction +'/web/uc/order/list';
                        },
                        btn2:function (index,ele) {
                            window.location.href = baseloaction +'/web/uc/order/list';
                        }
                    });
                    window.open(baseloaction + result.url,'_blank');
                }else{
                    icModale(0,'',result.message);
                }
            },
            error:function (error) {
                icModale(0,'','系统错误，订单创建失败');
            }
        });
    });

    /**
     * 获取选中的支付类型
     * @return {string}
     */
    function getPayType() {
        var active = $(".pay-type-sel-box.active");
        if(active!=null && active.length > 0){
            return active.data('type');
        }
        return '';
    }

    /**
     * 获取选中的收货地址
     * @return {*}
     */
    function getAddressData() {
        var address = $("#user-address-list .user-address-list-box.active");
        if(address!=null && address.length >0){
            var addressId = address.data('id');
            var _address = address.data('address');
            var obj = {
                'addressId':addressId,
                'address':_address
            };
            return obj;
        }
        return null;
    }

    /**
     * 获取优惠券编码
     * @return {jQuery}
     */
    function getCouponCode() {
        var couponCode = $("#coupon-code").val();
        if(couponCode==null || $.trim(couponCode)=='' || typeof  couponCode =='undefined'){
            couponCode ='';
        }else{
            var _readonly = $("#coupon-code").attr('readonly');
            if(typeof _readonly =='undefined'){
                couponCode ='';
            }
        }
        return couponCode;
    }

    /**
     * 获取商品数据
     * @param  status
     * @param loadActivityCode 是否加载活动和优惠券
     */
    function getShopData(status,loadActivityCode) {
        var activityId = $("#activity-sel-box").val();
        if(activityId==null || $.trim(activityId)=='' || typeof  activityId =='undefined'){
            activityId = 0;
        }
        var couponCode = getCouponCode();
        $.ajax({
            url:baseloaction +'/web/uc/order/ajaxQueryShopList',
            type:'post',
            dataType:'text',
            data:{
                'orderType':orderType,
                'shopData':shopData,
                'activityId':activityId,
                'couponCode':couponCode
            },
            success:function (result) {
                $("#pay-type-list-box").html(result);
                //设置商品量
                $("#shop-num").text(shopNum);
                $("#sum-price").text(parseFloat(sumOldPrice).toFixed(2));
                if((sumDiscountPrice+sumActivityPrice)>0){
                    $("#yh-price").text(parseFloat(sumDiscountPrice+sumActivityPrice).toFixed(2)).parents("p").removeClass("hide");
                }else{
                    $("#yh-price").text("0.00");
                }
                if(sumMemberSubPrice>0){
                    $("#yhm-price").text(parseFloat(sumMemberSubPrice).toFixed(2)).parents("p").removeClass("hide");
                }else{
                    $("#yhm-price").text("0.00");
                }
                $("#freight-price").text(parseFloat(freightPrice).toFixed(2));
                $("#real-price").text(parseFloat(sumRealPrice).toFixed(2));

                //加载收货地址
                if(haveBook && status != true){
                    setTimeout(function () {
                        getUserAddressList();
                    },1000);
                }
                if(orderType=='COMMON'){//普通订单
                    if(activityCodeMessage !=null && $.trim(activityCodeMessage)!=''){
                        icModale(0,'',activityCodeMessage);
                        $("#activity-sel-box").val(0);
                    }
                    //判断默认是否选择中账号支付
                    var balance = $("#balance").val();
                    if(balance < sumRealPrice){
                        $(".user-account-box-1").hide();
                        $(".user-account-box-2").show();
                    }else{
                        //判断
                        if($("section[data-type].active").length==0){
                            $(".user-account-box-1").find(".pay-type-sel-box").addClass("active");
                        }
                        $(".user-account-box-1").show();
                        $(".user-account-box-2").hide();
                    }
                    if(loadActivityCode==true){
                        //加载优惠券和活动
                        getActivityCode();
                    }
                }
            },
            error:function (error) {
                icModale(0,'','系统错误，商品数据获取失败');
            }
        });
    }
    //活动列表
    var activityList = null;
    //优惠券列表
    var couponCodeList = null;
    //不重复加载活动
    var activityCodeStatus = true;
    //清空优惠和活动的选择
    function emptyActivityCode() {
        $("#activity-sel-box").val(0);
        $("#coupon-code-sel-box").val('');
        $("#coupon-code").val('');
        $("#but-sub-box").show();
        $("#but-cancel-box").hide();
    }
    /**
     * 加载优惠和活动
     */
    function getActivityCode() {
        $("#activity-code-list").html("");
        if(paramsList==null || paramsList.length<=0){
            return;
        }
        var params = paramsList;
        $.ajax({
            url:baseloaction +'/web/uc/order/getActivityCode',
            type:"post",
            dataType:'json',
            data:JSON.stringify(params),
            contentType:'application/json;charset=utf-8',
            success:function (result) {
                activityList = result.activityList;
                couponCodeList = result.couponCodeList;
                //设置活动数据
                setActivityList();
                //设置优惠券数据
                setCouponCodeList()
            },
            error:function (error) {
                icModale(0,'','系统错误，活动和优惠加载失败');
            }
        });
    }

    /**
     * 设置活动
     */
    function setActivityList() {
        if(activityList!=null && activityList!=''){
            var context = '<section class="pt10">';
            context +='<div class="clearfix pt10">';
            context +='<aside class="pull-left">';
            context +='<span class="fs20 c-warning"><i class="fa fa-flag"></i></span>';
            context +='<span class="ml10 fs20 c-333">促销活动</span>';
            context +='<span class="ml10 fs12 c-999">';
            context +='（您购买的课程满足以下）';
            context +='<small class="fs14 c-danger">'+activityList.length+'</small>';
            context +='个促销活动，请选择合适活动</span></aside></div>';
            context +='<div class="mt20 ml20 mr20">';
            context +='<div class="row">';
            context +='<section class="col-sm-6">';
            context +='<select class="form-control" id="activity-sel-box">';
            context +='<option value="0">选择活动</option>';
            $.each(activityList,function (index,activity) {
                var text = '';
                if(activity.activityType.indexOf('1')!=-1){
                    text = '满'+activity.askAmount+'减'+activity.subAmount;
                }
                if(activity.activityType.indexOf('2')!=-1){

                    if(activity.giftType.indexOf('1')!=-1){
                        text = '-满'+activity.askAmount+'赠';
                        text+='课程&nbsp;';
                       var courses = activity.course;
                        if(courses!=null){
                            var courseNames ="";
                            for(i=0;i<courses.length;i++){
                                courseNames +=courses[i].courseName+ ",";
                            }
                            courseNames = courseNames.substring(0, courseNames.length - 1);
                            if(courseNames!=null&&courseNames!=''){
                                text+="("+courseNames+")&nbsp;";
                            }
                        }
                    }
                    if(activity.giftType.indexOf('3')!=-1){
                        text+='&nbsp;赠'+activity.integral+'积分';
                    }
                }
                context +='<option value="'+activity.id+'">'+activity.activityName+text+'</option>';
            });
            context +='</select></section></div></div><hr></section>';
            $("#activity-code-list").append(context);
            $("#activity-code-list").show();
        }
    }

    /**
     * 设置优惠券
     */
    function setCouponCodeList() {
        var  context = '<section class="pt10">';
        context+='<div class="clearfix pt10">';
        context+='<aside class="pull-left">';
        context+='<span class="fs20 c-warning"><i class="fa fa-tags"></i></span>';
        context+='<span class="ml10 fs20 c-333 hand">优惠券</span>';
        context+='<span class="ml10 fs12 c-999">';
        context+='优惠券仅优惠于课程商品';
        context+='</span></aside></div>';
        context+='<div class="mt20 ml20 mr20">';
        context+='<div class="row">';
        context+='<section class="col-sm-7">';
        context+='<div class="alert alert-warning">';
        context+='<h6 class="mb20"><i class="fa fa-circle-o-notch"></i> 使用优惠券抵销部分现金</h6>';
        context+='<section class="row">';
        context+='<aside class="col-sm-3 text-right">';
        context+='<span>选择优惠券：</span>';
        context+='</aside>';
        context+='<div class="col-sm-8">';
        context+='<select class="form-control" id="coupon-code-sel-box" name="couponCode">';
        context+='<option value="">请选择优惠券</option>';
        if(couponCodeList !=null && couponCodeList !=''){
            $.each(couponCodeList,function (index,couponCode) {
                context+='<option value="'+couponCode.code+'">'+couponCode.coupon.title+'-满'+couponCode.coupon.minAmount;
                if(couponCode.coupon.type==2){//立减
                    context+='立减￥'+couponCode.coupon.limitAtion;
                }
                if(couponCode.coupon.type==1){//折扣
                    context+='打'+couponCode.coupon.limitAtion+'折';
                }
                context+='</option>';
            });
        }
        context+='</select></div></section>';
        context+='<div class="mt20">';
        context+='<section class="row">';
        context+='<aside class="col-sm-3 text-right">';
        context+='<span>优惠券编码：</span></aside>';
        context+='<div class="col-sm-8">';
        context+='<div class="form-inline">';
        context+='<div class="form-group">';
        context+=' <input type="text" placeholder="请输入优惠券编码" id="coupon-code" class="form-control"/>';
        context+='</div>';
        context+='<button class="btn btn-warning ml5" id="but-sub-box" type="button">确定</button>';
        context+='<button class="btn btn-warning ml5" id="but-cancel-box" style="display: none;" type="button">取消</button>';
        context+='</div></div></section></div></div></section></div></div><hr></section>';
        $("#activity-code-list").append(context);
        $("#activity-code-list").show();
    }

    /**
     * 更新购买量
     * @param em 操作的元素
     * @param type 1减，2加，3输入
     */
    function updateBuyNum(em, type) {
        var parent = em.parent("small").parent("span").parent("div").parent("aside").parent("section");
        var shopCartId = $(parent).find("[name='shopCartId']").val();
        var buyNum = 0;
        var buyNumEm = null;
        if (type == 1) {
            buyNum = $(em).next('input').val();
            if (buyNum < 2) {
                return;
            }
            buyNum--;
            buyNumEm = $(em).next('input');
        } else if (type == 2) {
            buyNum = $(em).prev("input").val();
            buyNum++;
            buyNumEm = $(em).prev('input');
        } else if (type == 3) {
            buyNum = em.val();
            var reg = /^[0-9]+$/;
            if (!reg.test(buyNum)) {
                buyNum = 1;
            }
            buyNumEm = em;
        }
        if (buyNum < 1) {
            buyNum = 1;
        }
        $(buyNumEm).val(buyNum);
        setTimeout(function () {
            var oldBuyNum = $(buyNumEm).val();
            _updateBuyNum(shopCartId, buyNum, oldBuyNum)
        }, 500);
    }

    //执行修改
    function _updateBuyNum(shopCartId, buyNum, oldBuyNum) {
        if (buyNum != oldBuyNum) {
            return;
        }
        if (shopCartId != null && $.trim(shopCartId) != '' && shopCartId > 0) {
            $.ajax({
                url: baseloaction + '/web/uc/shopCar/updateShopCartNum',
                type: 'post',
                dataType: 'json',
                data: {
                    "shopCartId": shopCartId,
                    'buyNum': buyNum
                },
                success: function (result) {
                    if (result.success == false) {
                        icModale(0, "", result.message);
                    } else {
                        emptyActivityCode();
                        //重新加载商品数据列表
                        getShopData(true,true);
                    }
                },
                error: function (error) {
                    icModale(0, "", "系统错误，更新图书购买量失败");
                }
            });
        }else{
            var dataList = $("#shop-list-box>section.order-course-item");
            if(dataList!=null && dataList.length >0){
                shopData = dataList.map(function () {
                    var _shopData = $(this).find('input[name="shopId"]').val()+'-'+$(this).find('input[name="shopType"]').val()+'-'+$(this).find('input[name="buyNum"]').val();
                    return _shopData;
                }).get().join(",");
                emptyActivityCode();
                getShopData(true,true);
            }
        }
    }
});

/**
 * 保存用户地址信息
 */
function saveAddressCallback(){
    getUserAddressList();
}

/**
 * 获取用户收货地址
 */
function getUserAddressList() {
    //如果有图书商品的情况下，查询用户收货地址
    $.ajax({
        url:baseloaction +'/web/uc/order/getUserAddressList',
        type:'post',
        dataType:'text',
        success:function (result) {
            $("#user-address-list").html(result);
            $("#user-address-list").show();
        },
        error:function (error) {
            icModale(0,'','系统错误，用户收货地址获取失败');
        }
    });
}